package com.dcjt.firehotcarpad.moudle

import com.dcjt.firehotcarpad.R
import com.dcjt.firehotcarpad.base.BaseActivity
import com.dcjt.firehotcarpad.entity.DictEntity
import com.dcjt.firehotcarpad.model.ScreeningViewModel
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.ViewModelProviders
import com.allen.library.SuperTextView
import com.allen.library.SuperTextView.OnSuperTextViewClickListener
import com.aries.library.fast.manager.LoggerManager
import com.aries.library.fast.util.ToastUtil
import com.aries.ui.view.radius.RadiusEditText
import com.aries.ui.view.title.TitleBarView
import com.aries.ui.widget.action.sheet.UIActionSheetView
import com.aries.ui.widget.action.sheet.UIActionSheetView.OnSheetItemListener
import com.aries.ui.widget.progress.UIProgressView
import com.dcjt.firehotcarpad.adapter.FlowTagAdapter
import com.dcjt.firehotcarpad.base.ApiPath
import com.dcjt.firehotcarpad.entity.BaseEntity
import com.dcjt.firehotcarpad.entity.SearchHistoryEntity
import com.dcjt.firehotcarpad.manager.DataManager
import com.dcjt.firehotcarpad.utils.PickUtil
import com.dcjt.firehotcarpad.utils.StringUtils
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagFlowLayout

import kotlinx.android.synthetic.main.activity_screening.*
import java.text.SimpleDateFormat


/**
 * 赛选
 */
class ScreeningActivity : BaseActivity() {

    private var dialog: UIProgressView? = null
    private var dictTypeList: List<DictEntity>? = null
    private var dictAJDJList: List<DictEntity>? = null
    private var ajdj:String? = ""
    private var ajdjdm:String? = ""
    private var ajlx:String? = ""
    private var ajlxdm:String? = ""
    private var dictInfoList_str= mutableListOf<String>()
    private var dictAJDJList_str= mutableListOf<String>()
    override fun getContentLayout() = R.layout.activity_screening
    private lateinit var screeningViewModel: ScreeningViewModel
    private lateinit var ret_Search:RadiusEditText

    @SuppressLint("ResourceAsColor")
    override fun setTitleBar(titleBar: TitleBarView?) {
        titleBar?.setRightText("取消")
            ?.setTitleMainTextSize(this.resources.getDimension(R.dimen.main_size))
//            ?.setRightTextBackgroundColor(this.resources.getColor(R.color.mainColor))
        val  searchView   = LayoutInflater.from(this).inflate(R.layout.layout_serach_select, null)  as View
////        titleBar?.addRightAction(titleBar?.ViewAction(LayoutInflater.from(this).inflate(R.layout.layout_serach_item, null)),0)
        titleBar?.addRightAction(titleBar?.ViewAction(searchView),0)
        //tv_search_cancel
        var tv_Cancel = searchView.findViewById<TextView>(R.id.tv_search_cancel)
        ret_Search = searchView.findViewById<RadiusEditText>(R.id.ret_search)
        var search_del = searchView.findViewById<ImageView>(R.id.iv_search_del)
        ret_Search.addTextChangedListener(object: TextWatcher {
            override fun afterTextChanged(s: Editable?) {
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s?.length!! > 0){
                    search_del.visibility = View.VISIBLE
                } else{
                    search_del.visibility = View.INVISIBLE
                }
            }

        })
        search_del.setOnClickListener {
            ret_Search.text.clear()
        }
        tv_Cancel.setOnClickListener {
            finish()
        }
        rtv_search.setOnClickListener {
            if (!stv_select_type.centerString.startsWith("请选择")
                ||!stv_select_level.centerString.startsWith("请选择")
                ||!stv_select_time_end.centerString.startsWith("请选择")
                ||!stv_select_time_start.centerString.startsWith("请选择")
                ||ret_Search.text.trim().length>0
            ){
                var intent = Intent()
                intent.putExtra("ajdj", ajdj)
                intent.putExtra("ajdjdm", ajdjdm)
                intent.putExtra("ajlx", ajlx)
                intent.putExtra("ajlxdm", ajlxdm)
                intent.putExtra("startime", if(stv_select_time_start.centerString.startsWith("请选择")) "" else stv_select_time_start.centerString)
                intent.putExtra("endtime", if(stv_select_time_end.centerString.startsWith("请选择")) "" else stv_select_time_start.centerString)
                intent.putExtra("keyword",if(ret_Search.text.toString().trim().length==0) "" else ret_Search.text.toString().trim() )
                this@ScreeningActivity.setResult(ApiPath.RESULT_OK, intent)
                finish()
            } else{
                ToastUtil.show("请完善选择")
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        dialog?.setCancelable(false)
        screeningViewModel = ViewModelProviders.of(this).get(ScreeningViewModel::class.java)
        initSuperTextSelect()

        initLiveData()

        val searchHistroyList :List<SearchHistoryEntity> = DataManager.getInstance().searchHistroy

        var adpter = FlowTagAdapter(this,searchHistroyList)
        id_flowlayout.setAdapter(adpter)
        id_flowlayout.setMaxSelectCount(1)

        id_flowlayout.setOnTagClickListener(object : TagFlowLayout.OnTagClickListener{
            override fun onTagClick(view: View?, position: Int, parent: FlowLayout?): Boolean {
                if (view != null ) {
                    adpter.onSelected(position,view)
                }
                return true
            }
        })
        id_flowlayout.setOnSelectListener(TagFlowLayout.OnSelectListener { selectPosSet ->
            if (selectPosSet.size != 0){
                LoggerManager.e("select-----"+searchHistroyList.get(  selectPosSet.iterator().next()))
                //替换 textview 中的数据
                var  entity = searchHistroyList.get(  selectPosSet.iterator().next())
                if (entity!= null){
                    //等级
                    if ( entity.ajdj!= null){
                        ajdj = entity.ajdj
                        ajdjdm = entity.ajdjmc
                        stv_select_level.setCenterString(StringUtils.getNoNullString(ajdjdm,"请选择"))
                    }

                    //类型
                    if ( entity.ajlx != null){
                        ajlx = entity.ajlx
                        ajlxdm = entity.ajlxmc
                        StringUtils.getNoNullString(ajlxdm,"请选择")
                    }

                    //keyword
                    if (entity.keyword != null){
                        ret_Search.setText(entity.keyword)
                    }
                }
            }

        })

    }

    private fun initSuperTextSelect() {

        stv_select_type.setOnSuperTextViewClickListener(OnSuperTextViewClickListener {
            if (dictTypeList == null || dictTypeList.isNullOrEmpty()) {
                dictTypeList = DataManager.getInstance().getDictInfo("AJLX")
            }
            if(dictTypeList!!.size>0){
                showAJLXSelect()
            } else{
                screeningViewModel.getDictList("AJLX",mContext)
            }

        })
        stv_select_level.setOnSuperTextViewClickListener(OnSuperTextViewClickListener {
            if (dictAJDJList == null || dictAJDJList.isNullOrEmpty()) {
                dictAJDJList = DataManager.getInstance().getDictInfo("ZHDJ")
            }
            if (dictAJDJList!!.size>0){
                showAJDJSelect()
            } else{
                screeningViewModel.getDictList("ZHDJ",mContext)
            }

        })
        stv_select_time_end.setOnSuperTextViewClickListener {
            setSelectDate(it)
        }
        stv_select_time_start.setOnSuperTextViewClickListener {
            setSelectDate(it)
        }
    }

    private fun showAJLXSelect() {

        if (!dictTypeList.isNullOrEmpty()) {
            if (dictInfoList_str.size == 0) {
                (dictTypeList as MutableList<DictEntity>?)?.forEach {
                    dictInfoList_str.add(it.dict_value)
                }
            }

            UIActionSheetView(mContext)
                .setTitle("案件类型")
                .setItems(dictInfoList_str as List<CharSequence>?, OnSheetItemListener { i: Int ->
                    stv_select_type.setCenterString(
                        (dictTypeList as MutableList<DictEntity>?)?.get(
                            i
                        )?.dict_value
                    )
                    ajlx = (dictTypeList as MutableList<DictEntity>?)?.get(
                        i
                    )?.dict_key
                    ajlxdm = (dictTypeList as MutableList<DictEntity>?)?.get(
                        i
                    )?.dict_value
                })

                .setCancelMessage("取消")
                .show()
        }
    }

    private fun showAJDJSelect() {

        if (!dictAJDJList.isNullOrEmpty()) {
            if (dictAJDJList_str.size == 0) {
                (dictAJDJList as MutableList<DictEntity>?)?.forEach {
                    dictAJDJList_str.add(it.dict_value)
                }
            }

            UIActionSheetView(mContext)
                .setTitle("案件等级")
                .setItems(dictAJDJList_str as List<CharSequence>?, OnSheetItemListener { i: Int ->
                    stv_select_level.setCenterString(
                        (dictAJDJList as MutableList<DictEntity>?)?.get(
                            i
                        )?.dict_value
                    )
                    ajdj = (dictAJDJList as MutableList<DictEntity>?)?.get(i)?.dict_key
                    ajdjdm = (dictAJDJList as MutableList<DictEntity>?)?.get(i)?.dict_value
                })

                .setCancelMessage("取消")
                .show()
        }
    }


    private fun initLiveData() {
        screeningViewModel.requestStatusLiveData.observe(this@ScreeningActivity, androidx.lifecycle.Observer {
            dialog?.dismiss()
            it?.let {
                when (it.code) {
                    BaseEntity.ok -> {
                        DataManager.getInstance().saveDictInfo(it.data)
                        when(it.data.get(0).code){
                            "ZHDJ" ->    showAJDJSelect()
                            "AJLX" ->    showAJLXSelect()
                            else -> ToastUtil.show(it.data.get(0).code)
                        }

                    }
                    BaseEntity.err -> {
                        ToastUtil.show("服务器开小差了,请稍后再试!")
                    }
                    else -> {
                        ToastUtil.show("服务器开小差了,请稍后再试!", false)
                    }
                }
            }
        })
    }

    fun setSelectDate(selectDate: SuperTextView) {
        PickUtil.selectDate(
            mContext, { date ->
                selectDate.setCenterString(
                    SimpleDateFormat("yyyy-MM-dd").format(date)
                )
            })
    }


    override fun getOrientation(): Int {
        return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
    }
}
